import express from 'express'
import nodeAjax from './nodeAjax'

import {appid} from '../config'

// Create express router
const router = express.Router()

let backPath = '/'
let referrerId = ''

// Transform req & res to have the same API as express
// So we can use res.status() & res.json()
const app = express()
router.use((req, res, next) => {
  Object.setPrototypeOf(req, app.request)
  Object.setPrototypeOf(res, app.response)
  req.res = res
  res.req = req
  next()
})

router.get('/auth', (req, res, next) => {
  backPath = getQuery(req.url, 'backPath')
  referrerId = getQuery(backPath, 'referrerId')

  // console.log('referrerId:', referrerId)
  const host = req.headers.host

  const backUrl = encodeURIComponent(
    `http://${host}/api/token`
    // 'http://192.168.0.104:8888/dispatch/token'
  )
  // const appid = 'wxc60cfe941cf04cd0' // 线上
  // const appid = 'wxede20d9286db6756'

  const wxAuthUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${backUrl}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
  res.redirect(wxAuthUrl)
  // res.status(401).json({ message: 'Bad credentials' })
})

// Add POST - /api/logout
// router.post('/logout', (req, res) => {
//   delete req.session.authUser
//   res.json({ ok: true })
// })

router.get('/token', (req, res) => {
  // const backPath = getQuery(req.url, 'backPath') || ''

  // console.log('backPath:', backPath)

  const url = req.url
  const codeStr =
    url
      .split('?')[1]
      .split('&')
      .find(str => str.includes('code')) || ''
  const code = codeStr.split('=')[1]
  if (code) {
    nodeAjax.post('/api/auth/weixin/login', { code, referrerId }, '', data => {

      const accessToken = JSON.parse(data).msg

      req.session.accessToken = accessToken
      res.redirect(backPath)
    })
  }
})
// Add POST - /api/login
router.post('/login', (req, res) => {
  if (req.body.username === 'demo' && req.body.password === 'demo') {
    req.session.authUser = { username: 'demo' }
    return res.json({ username: 'demo' })
  }
  res.status(401).json({ message: 'Bad credentials' })
})

// Add POST - /api/logout
router.post('/logout', (req, res) => {
  delete req.session.authUser
  res.json({ ok: true })
})

// Export the server middleware
export default {
  path: '/api',
  handler: router
}

function getQuery(url, queryName) {
  if (!url.includes('?')) return ''

  const queryStr =
    url
      .split('?')[1]
      .split('&')
      .find(str => str.includes(queryName)) || ''
  const query = queryStr.split('=')[1]
  return decodeURIComponent(query)
}
